<!-- 个人术语缩略语库 -->
<template>
  <div class="editor-business-page" :class="{ expand: topLevel }">
    <div class="search">
      <el-button type="primary" size="small" @click="handleAdd">新增</el-button>
      <el-form
        :model="queryParams"
        ref="queryForm"
        :inline="true"
        size="small"
        label-suffix=":"
      >
        <el-form-item label="术语/缩略语中文" prop="nameZh">
          <el-input
            v-model="queryParams.nameZh"
            placeholder="请输入"
            clearable
            maxlength="100"
            style="width: 140px"
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="术语/缩略语英文" prop="nameEn">
          <el-input
            v-model="queryParams.nameEn"
            placeholder="请输入"
            clearable
            maxlength="100"
            style="width: 140px"
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="缩略词" prop="nameShort">
          <el-input
            v-model="queryParams.nameShort"
            placeholder="请输入"
            clearable
            maxlength="100"
            style="width: 140px"
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item class="btn-group">
          <el-button @click="handleQuery" type="primary" size="small"
            >搜索</el-button
          >
          <el-button plain @click="resetQueryParams" size="small"
            >重置</el-button
          >
        </el-form-item>
      </el-form>
    </div>
    <div class="content">
      <el-tabs v-model="dataType" type="card">
        <el-tab-pane :name="'0'" label="术语"></el-tab-pane>
        <el-tab-pane :name="'1'" label="缩略语"></el-tab-pane>
      </el-tabs>
      <el-table v-loading="loading" :data="dataList">
        <el-table-column
          label="序号"
          type="index"
          width="50"
          :index="indexMethod"
        />
        <el-table-column
          v-if="dataType === '1'"
          label="缩略词"
          width="160"
          prop="nameShort"
          key="abb"
          resizable
        />
        <el-table-column
          v-if="dataType === '0'"
          label="中文名称"
          min-width="120"
          prop="nameZh"
          key="zhName"
          resizable
        />
        <el-table-column
          :label="dataType === '0' ? '英文名称' : '英文全称'"
          min-width="200"
          prop="nameEn"
          key="enName"
          resizable
        />
        <el-table-column
          v-if="dataType === '1'"
          label="中文释义"
          min-width="200"
          prop="description"
          key="description"
          resizable
        />
        <el-table-column
          v-if="dataType === '0'"
          label="缩略词"
          width="160"
          prop="nameShort"
          key="nameShortTerm"
          resizable
        />
        <el-table-column
          label="状态"
          width="80"
          key="toggle"
          resizable
        >
          <template v-slot="scope">
            <el-switch
              v-model="scope.row.status"
              v-hasPermi="[dataType === '0'?'editor:termsInfo:change':'editor:abbreviationInfo:change']"
              @change="onStatusChange(scope.row)"
            ></el-switch>
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" width="190" key="option">
          <template v-slot="scope">
            <el-button type="text" @click="handleEdit(scope.row)"
              v-hasPermi="[dataType === '0'?'editor:termsInfo:editInfo':'editor:abbreviationInfo:edit']"
              >编辑信息</el-button
            ><el-button type="text" v-if="dataType === '0'" @click="goUpdate(scope.row)"
              v-hasPermi="['editor:termsInfo:editContent']"
              >编辑定义</el-button
            >
            <el-button type="text" @click="handleDelete(scope.row)"
              v-hasPermi="['editor:termsInfo:remove']"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        class="business-pager p20 fr"
        v-show="dataTotal > 0"
        :background="true"
        :current-page.sync="queryParams.pageNum"
        :page-size.sync="queryParams.pageSize"
        :layout="'total, sizes, prev, pager, next, jumper'"
        :page-sizes="[10, 30, 50, 100]"
        :pager-count="7"
        :total="dataTotal"
        @size-change="handleSizeChange"
        @current-change="handlepageNumChange"
      />
    </div>
    <EditTermModal
      :visible.sync="addModalVisible"
      @onSuccess="onAddSuccess"
      @update:visible="editData=null"
      :editData="editData"
    />
    <TermUpdateModal
      :visible.sync="termUpdateModalVisible"
      :updateData="updateData"
      @success="handleQuery"
    />
  </div>
</template>
<script>
import EditTermModal from "@/views/editor/__components__/TermEditModal.vue";
import TermUpdateModal from "@/views/editor/__components__/TermUpdateModal.vue";
import { publishTerms } from "@/api/business";
import {
  getMyTermList,
  getMyAbbreviationList,
  deleteMyTerm,
  deleteMyAbbreviation,
  switchTermStatus,
  switchAbbreviationStatus,
} from "@/api/business";
import { Message, MessageBox } from "element-ui";

export default {
  components: { TermUpdateModal, EditTermModal },
  data() {
    return {
      topLevel: false,
      queryParams: {
        nameZh: "",
        nameEn: "",
        nameShort: "",
        pageNum: 1,
        pageSize: 10,
      },
      addModalVisible: false,
      termUpdateModalVisible: false,
      loading: false,
      dataType: "0",
      dataList: [],
      dataTotal: 0,
      updateData: {},
      editData: null,
      // 是否支持临时术语缩略语
      enableTemporary: false,
    };
  },
  watch: {
    dataType(val) {
      this.dataList = [];
      this.dataTotal = 0;
      this.handleQuery();
    },
  },
  mounted() {
    this.handleQuery();
    let parentPath = window?.parent?.location?.pathname;
    if (parentPath == "/stp/abbreviation/index") {
      this.topLevel = true;
    } else {
      this.topLevel = false;
    }
  },
  methods: {
    indexMethod(index) {
      return (
        (this.queryParams.pageNum - 1) * this.queryParams.pageSize + index + 1
      );
    },
    hasPermission(value) {
      return true;
      // const value = ['term:topublish']
      const all_permission = "*:*:*";
      const permissions = JSON.parse(
        sessionStorage.getItem("stpPermission") || "[]"
      );
      if (value && value instanceof Array && value.length > 0) {
        const permissionFlag = value;
        const hasPermissions = permissions.some((permission) => {
          return (
            all_permission === permission || permissionFlag.includes(permission)
          );
        });
        if (!hasPermissions) {
          return false;
        }
        return true;
      }
      return false;
    },
    resetQueryParams() {
      this.$refs.queryForm.resetFields();
      this.queryParams.pageNum = 1;
      this.handleQuery();
    },
    refresh() {
      this.queryParams.pageNum = 1;
      this.handleQuery();
    },
    handleQuery() {
      this.loading = true;
      const call =
      this.dataType === '0'
          ? getMyTermList
          : getMyAbbreviationList;
      call(this.queryParams)
        .then((res) => {
          this.dataList = res.data.list.map((item, index) => ({
            ...item,
            order: index + 1,
            status: Number(item.status) ? true : false,
          }));
          this.dataTotal = res.data.count;
        })
        .finally(() => {
          this.loading = false;
        });
    },
    handleSizeChange(val) {
      if (this.queryParams.pageSize * val > this.dataTotal) {
        this.queryParams.pageNum = 1;
      }
      this.handleQuery();
    },
    handlepageNumChange() {
      this.handleQuery();
    },
    goUpdate(row) {
      window.open(`/editor/view?id=${row.id}&editContentType=block&entry=termblock`, "_blank");
    },
    handleAdd() {
      this.addModalVisible = true;
    },
    async handleDelete(row) {
      try {
        await MessageBox.confirm(`此操作将删除数据，是否继续？`, '提示', {
          type: 'warning'
        })
        if (this.dataType === "0") {
          await deleteMyTerm(row.id)
        } else {
          await deleteMyAbbreviation(row.id)
        }
        Message.success("删除成功");
        this.handleQuery();
      } catch (error) {
        console.debug(error);
      }
    },
    // 编辑术语/缩略语
    handleEdit(row) {
      this.editData = {
        ...row,
        type: this.dataType === "0" ? "TERM" : "ABBREVIATION",
      };
      this.addModalVisible = true;
    },
    // 新增完成后刷新
    onAddSuccess(type) {
      this.dataType = type === "TERM" ? "0" : "1";
      this.handleQuery();
    },
    handleUpdate(row) {
      this.updateData = row;
      this.termUpdateModalVisible = true;
    },
    async handlePublish() {
      try {
        await publishTerms();
        this.refresh();
        Message.success("发布成功");
      } catch (error) {
        Message.error("发布失败");
      }
    },
    // 切换术语/缩略语状态
    onStatusChange(item) {
      const call =
        this.dataType === "0" ? switchTermStatus : switchAbbreviationStatus;
      call({
        id: item.id,
        status: item.status ? "1" : "0",
      })
        .then((res) => {
          Message.success(item.status ? "开启成功" : "禁用成功");
        })
        .finally(() => {
          this.handleQuery();
        });
    },
  },
};
</script>
<style lang="scss" scoped>
@import "~@/assets/styles/editor.scss";
.editor-business-page .search {
  justify-content: space-between;
}
::v-deep .el-form-item--small.el-form-item {
  margin-bottom: 0;
}
.expand {
  width: calc(100vw - 20px);
  margin: 0 auto;
}
.content {
  padding: 24px;
}
.content .controls {
  margin-bottom: 24px;
}
.tips {
  font-size: 12px;
  color: red;
}
.btn-row {
  margin-bottom: 10px;
}
</style>
